import React, { Component } from 'react'


import MyBtn from './MyBtn'


export default class MyLife extends Component {
  state = {
    flag: true
  }



  render() {
    const { flag } = this.state
    return (
      <div>
        <h3>React 生命周期</h3>
        {
          flag && <Mychild msg='你就像天外来物一样，求之不得'></Mychild>
        }
        <MyBtn text='销毁子组件' onClick={() => { this.setState({ flag: !flag }) }}></MyBtn>
      </div>
    )
  }

  componentDidMount() {
    console.log('父组件 - 初始化加载');
  }
}

let index = 0
class Mychild extends Component {

  log = (msg) => {
    console.log(`#${++index} --- ${msg}`);
  }

  constructor() {
    super()
    this.log('constructor - 构造函数初始化')
  }

  static getDerivedStateFromProps(props, state) {
    console.log(props);
    console.log(state);

    console.log(`#${++index} --- ${'getDerivedStateFromProps 获取新的state从props'}`);

    return {
      a: 3090,
      ...props
    }
  }


  state = {
    count: 100,
    word: '无奈的请背过手'
  }

  change = () => {
    this.setState({
      count: this.state.count + 1
    })
  }


  // SCU优化 性能优化
  shouldComponentUpdate(props, state) {
    console.log(props, state); // 新值
    console.log(this.props, this.state); // 旧值

    this.log('shouldComponentUpdate - 询问是否更新')
    if (this.state.word !== state.word) {
      return true
    } else {
      return false
    }
  }

  render() {
    const { count, word } = this.state
    return (
      <div>
        <h3>Mychild - Mychild</h3>
        <h4>count = {count}</h4>
        <h4>word = {word}</h4>

        <MyBtn text='change Count' onClick={this.change}></MyBtn>
        <br />
        <div>
          <input type='text' ref={el => this.one = el} value={word} onChange={() => this.setState({ word: this.one.value })} />
        </div>
        <br />
      </div>
    )
  }

  // 获取到更新之前的旧数据
  getSnapshotBeforeUpdate(props, state) {
    console.log(props, state); // 旧值
    console.log(this.props, this.state); // 新值

    this.log('getSnapshotBeforeUpdate - 获取到更新之前的旧数据')
    return {
      b: 4090,
      ...state
    }
  }

  componentDidUpdate(props, state, oldState) {
    console.log(props, state, oldState);
    this.log('componentDidUpdate - 组件已经完成二次更新')
  }


  // ***重点
  componentDidMount() {
    // 插件实例化
    // 请求 ajax
    this.log('componentDidMount - 组件初始化载入')
  }

  componentWillUnmount() {
    this.log('componentWillUnmount - 组件销毁')
  }
}



